package pingpongdojo.auth;

import java.util.Map;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.commands.ICommandService;
import org.eclipse.ui.commands.IElementUpdater;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.ui.menus.UIElement;
import org.eclipse.ui.services.ISourceProviderService;

import pingpongdojo.model.ModelFactory;

public class LogoutHandler extends AbstractHandler implements IElementUpdater {
	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {

		// perform login here ...
		System.err.println("Logout handler executed");

		IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
		ISourceProviderService service = (ISourceProviderService) window
				.getService(ISourceProviderService.class);
		SessionSourceProvider sessionSourceProvider = (SessionSourceProvider) service
				.getSourceProvider(SessionSourceProvider.SESSION_STATE);

		// update the source provider
		sessionSourceProvider.setLoggedIn(false);

		// Update the login/logout menu
		ICommandService commandService = (ICommandService) PlatformUI
				.getWorkbench().getService(ICommandService.class);

		commandService
				.refreshElements("pingpongdojo.auth.sessionCommand", null);

		ModelFactory.getInstance().getGameManager().setCurrentGame(null);
		return null;
	}

	@Override
	public void updateElement(UIElement element, Map parameters) {
		element.setText("Logout");
	}
}